package com.controller;

import com.api.CommonResult;
import com.entity.*;
import com.entity.table.FAddressTableDef;
import com.entity.table.FCartGoodsTableDef;
import com.entity.table.FCartTableDef;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.service.FAddressService;
import com.service.FCartGoodsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.service.FCartService;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 *  控制层。
 *
 * @author admin
 * @since 2024-05-30
 */
@Controller
@RequestMapping("/fCart")
public class FCartController {

    @Autowired
    private FCartService fCartService;
    @Autowired
    private FCartGoodsService fCartGoodsService;
    @Autowired
    private FAddressService fAddressService;

    /**
     * 添加。
     *
     * @param fCart 
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    @ResponseBody
    @Transactional
    public CommonResult save(FCart fCart, int goodId, HttpServletRequest request) {
       try {
           HttpSession session = request.getSession();
           //读取服务器缓存，获取当前用户的登录信息
           FUser user = (FUser) session.getAttribute("user");
           fCart.setUserId(user.getId());
           FCart fCart1 = fCartService.getUserCartInfo(user.getId());
           if(fCart1 != null){//购物车不为空
               Optional<BGoods> bGoods = fCart1.getGoods().stream()
                       .filter(item -> item.getId().equals(goodId)).findFirst();
               if (bGoods.isPresent()){
                   //商品已加入购物车，对应商品总数相加
                   QueryWrapper query = QueryWrapper.create().where(FCartGoodsTableDef.F_CART_GOODS.GOODS_ID.eq(goodId))
                           .and(FCartGoodsTableDef.F_CART_GOODS.CART_ID.eq(fCart1.getId()));
                   FCartGoods fCartGoods = fCartGoodsService.getOne(query);
                   fCartGoods.setNum(fCartGoods.getNum()+fCart.getNum());
                   fCartGoodsService.updateById(fCartGoods);
               }
               else {
                   //添加商品到购物车
                   FCartGoods fCartGoods = new FCartGoods();
                   fCartGoods.setCartId(fCart1.getId());
                   fCartGoods.setGoodsId(goodId);
                   fCartGoods.setNum(fCart.getNum());
                   fCartGoodsService.save(fCartGoods);
               }
               //购物车商品总数增加
               fCart1.setNum(fCart1.getNum()+fCart.getNum());
               fCartService.updateById(fCart1);
           }
           else {
               //购物车为空，添加购物车数据
               FCart newCart = new FCart();
               newCart.setNum(fCart.getNum());
               newCart.setUserId(user.getId());
               fCartService.save(newCart);
               //添加用户购物车商品
               FCartGoods fCartGoods = new FCartGoods();
               fCartGoods.setCartId(newCart.getId());
               fCartGoods.setGoodsId(goodId);
               fCartGoods.setNum(fCart.getNum());
               fCartGoodsService.save(fCartGoods);
           }
        } catch (Exception e) {
           e.printStackTrace();
           //数据库出错回滚
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           CommonResult.failed("添加购物车失败");
       }
       return CommonResult.success("商品已添加到购物车");
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return fCartService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param fCart 
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody FCart fCart) {
        return fCartService.updateById(fCart);
    }

    /**
     * 修改查询所有，显示购物车数据
     *
     * @return 所有数据
     */
    @GetMapping("")
    public String list(Model model,HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            //从服务器内存读取用户信息
            FUser user = (FUser) session.getAttribute("user");
            QueryWrapper query = QueryWrapper.create().where(FCartTableDef.F_CART.USER_ID.eq(user.getId()));
            FCart fCart = fCartService.getMapper().selectOneWithRelationsByQuery(query);
            if (fCart != null){
                BigDecimal totalPrice = new BigDecimal(0);//记录商品总价
                for (BGoods good : fCart.getGoods()) {
                    BGoods good1 = fCartGoodsService.getTotalPriceByGood(fCart.getId(), good);
                    totalPrice = totalPrice.add(good1.getTotalPrice());
                }
                fCart.setTotalPrice(totalPrice);
            }
            model.addAttribute("user",user);
            model.addAttribute("cart",fCart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "client/cart";
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public FCart getInfo(@PathVariable Serializable id) {
        return fCartService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<FCart> page(Page<FCart> page) {
        return fCartService.page(page);
    }

    //购物车点击去结算
    @GetMapping(value = "/placeOrder")
    public String placeOrder(HttpServletRequest request, ModelMap model) {
        HttpSession session = request.getSession();
        FUser user = (FUser) session.getAttribute("user");
        //读取收获地址
        FAddress fAddress = fAddressService.queryChain().where(FAddressTableDef.F_ADDRESS.USER_ID.eq(user.getId())).one();
        //读取购物车
        FCart fCart = fCartService.getUserCartInfo(user.getId());
        model.addAttribute("fAddress", fAddress);
        model.addAttribute("cart", fCart);
        model.addAttribute("totalPrice", fCart.getTotalPrice());//保留两位小数
        return "client/place_order";
    }
}
